import sqlite3
import json

"""
封装 Coze API 调用为函数，输入文本返回响应结果
"""
from cozepy import COZE_CN_BASE_URL
from cozepy import Coze, TokenAuth, Stream, WorkflowEvent, WorkflowEventType

# 全局配置
coze_api_token = 'pat_bkJmbt7cBmrNf8PeoRA4GjzIn3h9PJofkuCP5Wg9rfxXiwuc8C8WFRrplWt2cqVv'
coze_api_base = COZE_CN_BASE_URL
workflow_id = '7569130821820809252'

# 初始化 Coze 客户端
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)

def chat_with_coze(text: str) -> str:
    """
    向 Coze 工作流发送文本并返回响应结果
    
    Args:
        text (str): 要发送的文本内容
        
    Returns:
        str: Coze 工作流的响应内容
    """
    # 定义输入参数
    input_params = {
        "input": text  # 键必须匹配工作流定义的输入参数名
    }
    
    # 收集所有消息内容
    responses = []
    
    def handle_workflow_stream(stream: Stream[WorkflowEvent]):
        """处理工作流事件流"""
        for event in stream:
            if event.event == WorkflowEventType.MESSAGE:
                # 收集消息内容
                if hasattr(event, 'message') and hasattr(event.message, 'content'):
                    responses.append(event.message.content)
            elif event.event == WorkflowEventType.ERROR:
                error_msg = f"错误: {event.error.message}" if hasattr(event, 'error') else "未知错误"
                responses.append(error_msg)
            elif event.event == WorkflowEventType.INTERRUPT:
                # 处理中断事件
                handle_workflow_stream(
                    coze.workflows.runs.resume(
                        workflow_id=workflow_id,
                        event_id=event.interrupt.interrupt_data.event_id,
                        resume_data="继续",
                        interrupt_type=event.interrupt.interrupt_data.type,
                    )
                )
    
    # 执行工作流
    handle_workflow_stream(
        coze.workflows.runs.stream(
            workflow_id=workflow_id,
            parameters=input_params
        )
    )
    
    # 返回所有消息的合并结果
    return json.loads(''.join(responses) if responses else "未收到响应")

def find_matching_product(input_data):
    """
    根据输入数据查找匹配的产品
    
    参数:
    input_data: 输入的产品信息，可以是JSON字符串格式如：{"尺码":"S","款号":"AE000159","颜色":"黄"}
    
    返回:
    匹配到的产品列表，如果找到匹配则返回第一个匹配的产品
    """
    # 解析输入数据
    input_info = {}
    
    # 尝试解析JSON格式
    try:
        if isinstance(input_data, str):
            data = json.loads(input_data)
        else:
            data = input_data
        
        # 提取款号、颜色、尺码信息
        if '款号' in data:
            input_info['style'] = data['款号']
        if '颜色' in data:
            input_info['color'] = data['颜色']
        if '尺码' in data:
            input_info['size'] = data['尺码']
    except (json.JSONDecodeError, TypeError):
        # 如果JSON解析失败，尝试使用原来的文本格式
        lines = input_data.strip().split('\n')
        
        for line in lines:
            if ':' in line:
                key, value = line.split(':', 1)
                key = key.strip().replace('-', '').strip()
                value = value.strip()
                if key == '款号':
                    input_info['style'] = value
                elif key == '颜色':
                    input_info['color'] = value
                elif key == '尺码':
                    input_info['size'] = value
    
    # 连接数据库获取产品列表
    conn = sqlite3.connect('product.db')
    c = conn.cursor()   
    c.execute("SELECT sku FROM shang_pin_bian_ma")
    result = c.fetchall()
    database_products = [row[0] for row in result]
    conn.close()
    
    # 匹配产品
    matched_products = []
    
    for product in database_products:
        # 进行包含匹配
        style_match = input_info.get('style', '') in product
        color_match = input_info.get('color', '') in product
        size_match = input_info.get('size', '') in product
        
        if style_match and color_match and size_match:
            matched_products.append(product)
            # 如果匹配到第一个产品，立即返回，不再继续匹配
            if len(matched_products) == 1:
                return matched_products
    
    return matched_products

# 使用示例
if __name__ == "__main__":

    input_data = chat_with_coze("LB-TV00192-LAN-S")["output"]
    
    print(input_data)

    result = find_matching_product(input_data)
    print("匹配结果:", result)